import {getEtagHeaderAndData, setEtagHeaderAndData} from '../helper/dropdownlist'
import {AxiosInstance} from 'axios'
import {getAxiosErrCode} from '../helper/errorhandler'
import {ref, Ref} from 'vue'

export const labelAltTextsData: Ref<Record<string, string>> = ref({})

// 准备标签文本替换的数据（这个方法只需要在boot中调用1次即可）
export const getLabelAltTextsData = function (axios:AxiosInstance) {
  const apiPath = '/comm/utils/get-label-alt-texts'
  const localCache = getEtagHeaderAndData(apiPath)
  axios.get<Record<string, string>>(apiPath, {headers: localCache.headers})
    .then(result => {
      setEtagHeaderAndData(apiPath, result)
      labelAltTextsData.value = result.data
    })
    .catch(err => {
      if (getAxiosErrCode(err) === 304) {
        labelAltTextsData.value = JSON.parse(localCache.data!) as Record<string, string>
      }
      else{
        throw err
      }
    })
}

// 获取替换文本的方法
const altLabelTexts = function (sys: string, category: string, labelId: string, defText?: string): string {
  const key = sys + '#' + category + '#' + labelId
  return labelAltTextsData.value[key] ?? defText ?? labelId
}

// 准备一个方便的格式化的方法，例如： const T = prepareAltLabelTextsFunc('foundation', 'mf')
// 这样要替换文本就写成 {{T('user_def1','自定义1')}}
export const prepareAltLabelTextsFunc = function (sys: string, category: string): (labelId: string, defText?: string) => string {
  return (labelId: string, defText?: string) => {
    return altLabelTexts(sys, category, labelId, defText)
  }
}
